package com.lskj.shiro.controller;

import com.lskj.shiro.config.jwtconfig.JWTFilter;
import com.lskj.shiro.constant.Constant;
import com.lskj.shiro.entity.SysUser;
import com.lskj.shiro.service.ISysUserService;
import com.lskj.shiro.util.JWTUtil;
import com.lskj.shiro.util.RedisUtil;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

/**
 * @Author zzq
 * @Date 2020/4/3 16:33
 * @Version 1.0
 */
@RestController
@RequestMapping
public class LoginController {
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private RedisUtil redisUtil;

    @GetMapping("/login")
    public String login(@Param("userName") String userName, @Param("password") String password) {
        SysUser sysUser = sysUserService.getUserByUserName(userName);
        return Optional.ofNullable(sysUser).map(e -> {
            if (sysUser.getPassword().equals(password)) {
                setRedis(sysUser);
                return "登录成功";
            } else {
                return "密码错误";
            }
        }).orElse("用户不存在");
    }

    private void setRedis(SysUser sysUser) {
        String password = sysUser.getPassword();
        String userName = sysUser.getUserName();
        String sign = JWTUtil.sign(userName, password);
        redisUtil.set(sign, sign);
        redisUtil.expire(sign, Constant.REDIS_KEY_EXPIRE);
    }
}
